from django.shortcuts import render,redirect,HttpResponse
from django import views
from myApp import models
from django.db import connection
import json
import re
# Create your views here.

class test(views.View):
    def get(self,req,*args,**kwargs):
        # 插入数据库内容
        # models.teacher.objects.create(
        #     name="chen",
        #     sex='男',
        #     phonenum='13546789889',
        # )
        models.teacher.objects.all().last().classes.add(models.cls.objects.get(name='python全栈1班'))   # 多对多关联对象
        # data = models.cls.objects.get(name='python全栈2班').student_set.all()   # 反向查找，related_name可以设置反向查找名字,不设置默认是"从表_set"
        # models.teacher.objects.get(id='1').classes.remove(models.cls.objects.get(name='python全栈1班')) # 移除第三张中的关联对象
        # 清空关联对象用clear--models.teacher.objects.all().last().classes.clear()
        # 替换关联对象
        # L = [models.cls.objects.get(name='python全栈1班'),models.cls.objects.get(name='python全栈2班')]
        # models.teacher.objects.all().last().classes.set(L)
        # 1班由哪些老师带
        # data = models.cls.objects.get(name='python全栈1班').teacher_set.all()
        # 查找chen老师带的哪个班
        data = models.teacher.objects.get(name='chen').classes.all()
        return render(req,'test.html',{'data':data})

    def post(self,req,*args,**kwargs):
        pass

def clsOperation(req):
    op = req.POST.get("op",None)
    if op == 'del':
        clsname = req.POST.get("name", None)
        try:
            # models.cls.objects.raw('select * from myapp_cls where name=%s',[clsname])  # 使用占位符不需要加引号
            with connection.cursor() as cursor:
                cursor.execute('delete from myapp_cls where name=%s',[clsname])     # 使用原生的SQL语句，使用游标删除
        except Exception as f:
            return HttpResponse('err')
        return HttpResponse('OK')
    elif op == 'editClasses':
        formData = req.POST.get('formdata', None)
        formObj = json.loads(formData)
        try:
            models.cls.objects.filter(id=formObj['id']).update(name=formObj['clsname'],start=formObj['start'],progress=formObj['progress'],remark=formObj['remark'])
            teacherList = []
            for i in formObj['teachers']:
                teacherList.append(models.teacher.objects.get(name=i))
            models.cls.objects.get(id=formObj['id']).teacher_set.set(teacherList)
        except Exception as f:
            return HttpResponse('err')
        return HttpResponse("OK")
    elif op == 'editTeacher':
        clsData = req.POST.get('clsdata', None)
        clsObj = json.loads(clsData)
        try:
            models.teacher.objects.filter(id=clsObj['id']).update(name=clsObj['name'], sex=clsObj['sex'], phonenum=clsObj['phonenum'])
            classesList = []
            for j in clsObj['classes']:
                classesList.append(models.cls.objects.get(name=j))
            models.teacher.objects.get(id=clsObj['id']).classes.set(classesList)
        except Exception as f:
            return HttpResponse('err')
        return HttpResponse("OK")
    elif op == 'editStudent':
        clsidData = req.POST.get('clsiddata', None)
        clsidObj = json.loads(clsidData)
        try:
            models.teacher.objects.filter(id=clsidObj['id']).update(name=clsidObj['name'], sex=clsidObj['sex'],age=clsidObj['age'], phonenum=clsidObj['phonenum'],qq=clsidObj['qq'],school=clsidObj['school'],progress=clsidObj['progress'],job=clsidObj['job'],remark=clsidObj['remark'])
            # classesList = []
            # for j in clsidObj['classes']:
            #     classesList.append(models.cls.objects.get(name=j))
            # models.teacher.objects.get(id=clsidObj['id']).classes.set(classesList)
        except Exception as f:
            return HttpResponse('err')
        return HttpResponse("OK")
    elif op == 'getTeacher':
        teacherList = models.teacher.objects.raw('select * from myapp_teacher')
        L = []
        for i in teacherList:
            L.append(i.name)
        teachername = req.POST.get('name',None)
        ret =models.cls.objects.get(name=teachername)
        jsondata = json.dumps({'teachers':L,'id':ret.id})
        return HttpResponse(jsondata)
    elif op == 'getCls':
        classesList = models.cls.objects.raw('select * from myapp_cls')
        L = []
        for i in classesList:
            L.append(i.name)
        clsname = req.POST.get('name',None)
        ret =models.teacher.objects.get(name=clsname)
        jsondata = json.dumps({'clas':L,'id':ret.id})
        return HttpResponse(jsondata)
    elif op == 'getStudents':
        studentList = models.student.objects.raw('select * from myapp_student')
        L = []
        for i in studentList:
            L.append(i.name)
        stuname = req.POST.get('name', None)
        ret = models.teacher.objects.get(name=stuname)
        jsondata = json.dumps({'students': L, 'id': ret.id})
        return HttpResponse(jsondata)

def pagination(page,zPages,yNum):
    step = 0
    if page < 4:
        pageStart = 2
        if zPages >= 5:
            pageEnd = 5
            step = 1
        else:
            pageEnd = zPages
            step = 2
    elif page < zPages - 2:
        pageStart = page - 2
        pageEnd = page + 2
        step = 3
    else:
        step = 4
        if yNum != 0:
            pageStart = zPages - 3
            pageEnd = zPages + 1
        else:
            pageStart = zPages - 4
            pageEnd = zPages
    return [step,pageStart,pageEnd]

usrname = None
class login(views.View):
    def get(self,req,*args,**kwargs):
        return render(req, 'login.html')

    def post(self,req,*args,**kwargs):
        usrdata = req.POST.get("usr", None)
        pwddata = req.POST.get("pwd", None)
        iddata  = req.POST.get("id",None)
        try:
            models.usrinfo.objects.get(usr=usrdata,pwd=pwddata,uid=iddata)
        except Exception:
            return render(req,"login.html",{"errinfo":"登录失败，请检查用户名、密码或身份信息"})

        req.session["login"]=True
        req.session["usr"]=usrdata
        req.session["id"] = iddata
        req.session.set_expiry(1200)
        # return render(req,"student.html",{"usrname":req.session['usr']})
        return redirect("/student/1.html/")

class student(views.View):
    def get(self,req,*args,**kwargs):
        if not req.session.get("login",None):
            return redirect("/login/")
        student = models.student.objects.all()
        zPages, yNum = divmod(student.count(), 10)  # 得到整数和余数
        page = int(kwargs["page"].split(".")[0])
        start = (page - 1) * 10
        end = start + 10
        stu = student[start:end]
        p = pagination(page, zPages, yNum)

        pagenum = []
        pagenum.append('<a style="width: 60px;" href="/student/1.html/">首页</a>')
        if page != 1:
            pagenum.append('<a style="width: 60px;" href="/student/%d.html/">上一页</a>' % (page - 1))
            pagenum.append('<a href="/student/1.html/">1</a>')
        else:
            pagenum.append('<a style="background-color: darkgray;" href="/student/1.html/">1</a>')
        if p[0] > 1:
            pagenum.append('<a>...</a>')
        for i in range(p[1], p[2] + 1):
            if i == page:
                pagenum.append('<a style="background-color: darkgray;" href="/student/%d.html/">%d</a>' % (i, i))
            else:
                pagenum.append('<a href="/student/%d.html/">%d</a>' % (i, i))
        if p[0] > 0 and p[0] <= 3:
            pagenum.append('<a>...</a>')
        if page != zPages:
            pagenum.append('<a style="width: 60px;" href="/student/%d.html/">下一页</a>' % (page + 1))
        pagenum.append('<a style="width: 60px;" href="/student/%d.html/">尾页</a>' % (zPages))

        numshow = "".join(pagenum)
        return render(req, 'student.html',{"usrname":req.session['usr'], "addwhich":"student",'student':stu, 'pagenum':numshow})

    def post(self,req,*args,**kwargs):
        pass

class teacher(views.View):
    def get(self,req,*args,**kwargs):
        if not req.session.get("login", None):
            return redirect("/login/")
        teacher = models.teacher.objects.all()
        zPages, yNum = divmod(teacher.count(), 10)  # 得到整数和余数
        page = int(kwargs["page1"].split(".")[0])
        start = (page - 1) * 10
        end = start + 10
        tea = teacher[start:end]
        p = pagination(page, zPages, yNum)

        pagenum = []
        pagenum.append('<a style="width: 60px;" href="/teacher/1.html/">首页</a>')
        if page != 1:
            pagenum.append('<a style="width: 60px;" href="/teacher/%d.html/">上一页</a>' % (page - 1))
            pagenum.append('<a href="/teacher/1.html/">1</a>')
        else:
            pagenum.append('<a style="background-color: darkgray;" href="/teacher/1.html/">1</a>')
        if p[0] > 1:
            pagenum.append('<a>...</a>')
        for i in range(p[1], p[2] + 1):
            if i == page:
                pagenum.append('<a style="background-color: darkgray;" href="/teacher/%d.html/">%d</a>' % (i, i))
            else:
                pagenum.append('<a href="/teacher/%d.html/">%d</a>' % (i, i))
        if p[0] > 0 and p[0] <= 3:
            pagenum.append('<a>...</a>')
        if page != zPages:
            pagenum.append('<a style="width: 60px;" href="/teacher/%d.html/">下一页</a>' % (page + 1))
        pagenum.append('<a style="width: 60px;" href="/teacher/%d.html/">尾页</a>' % (zPages))

        numshow = "".join(pagenum)

        return render(req, 'teacher.html',{"usrname":req.session['usr'], "addwhich":"teacher", 'teacher':tea, "pagenum": numshow})


    def post(self,req,*args,**kwargs):
        pass

class classes(views.View):
    def get(self,req,*args,**kwargs):
        if not req.session.get("login", None):
            return redirect("/login/")
        # 添加数据，只能使用一次
        # for i in range(1,501):
        #     models.cls.objects.create(
        #         name="python全栈"+str(i)+"班",
        #         start="2018-06-15",
        #         progress="jquery",
        #     )
        classes = models.cls.objects.all()
        zPages,yNum = divmod(classes.count(), 20)  # 得到整数和余数
        page = int(kwargs["page"].split(".")[0])
        start = (page - 1) * 20
        end = start + 20
        cls = classes[start:end]
        p = pagination(page,zPages,yNum)

        pagenum = []
        pagenum.append('<a style="width: 60px;" href="/classes/1.html/">首页</a>')
        if  page != 1:
            pagenum.append('<a style="width: 60px;" href="/classes/%d.html/">上一页</a>' % (page - 1))
            pagenum.append('<a href="/classes/1.html/">1</a>')
        else:
            pagenum.append('<a style="background-color: darkgray;" href="/classes/1.html/">1</a>')
        if p[0] > 1:
            pagenum.append('<a>...</a>')
        for i in range(p[1],p[2] + 1):
            if i == page:
                pagenum.append('<a style="background-color: darkgray;" href="/classes/%d.html/">%d</a>' % (i, i))
            else:
                pagenum.append('<a href="/classes/%d.html/">%d</a>'%(i,i))
        if p[0] > 0 and p[0] <= 3:
            pagenum.append('<a>...</a>')
        if page != zPages:
            pagenum.append('<a style="width: 60px;" href="/classes/%d.html/">下一页</a>' % (page + 1))
        pagenum.append('<a style="width: 60px;" href="/classes/%d.html/">尾页</a>'%(zPages))

        numshow = "".join(pagenum)
        return render(req, 'classes.html',{"usrname":req.session['usr'], "addwhich":"classes", "classes":cls, "pagenum":numshow})

    def post(self,req,*args,**kwargs):
        pass

def blank(req):
    # return redirect('/login/')
    return render(req,"base.html")

codeid = 0
def add(req,which):
    if which == "property":
        if req.session.get("id", None) == '3':
            return HttpResponse("ok")
        else:
            return HttpResponse("err")
    else:
        if which == "student":
            global codeid
            clses = models.cls.objects.all()
            proviences = models.area.objects.filter(parentid=0)
            cityname = req.POST.get('pro', None)
            if cityname:
                codeid = models.area.objects.get(cityName=cityname, parentid=0).codeid
                cities = models.area.objects.filter(parentid=codeid)
                citystr = ""
                for i in cities:
                    citystr = citystr + i.cityName + ","
                return HttpResponse(citystr)

            countyname = req.POST.get('city', None)
            if countyname:
                codeid1 = models.area.objects.get(cityName=countyname, parentid=codeid).codeid
                counties = models.area.objects.filter(parentid=codeid1)
                countystr = ""
                for i in counties:
                    countystr = countystr + i.cityName + ","
                return HttpResponse(countystr)

            return render(req, "add.html", {"clses": clses, "proviences": proviences, "addwhich": which})








